<!--
  * OCR性能监控页面
  *
  * @Author:    1024创新实验室
  * @Date:      2024-12-19
  * @Wechat:    1024创新实验室
  * @Email:     1024lab@163.com
  * @Copyright  版权信息
-->
<template>
  <div class="ocr-performance-container">
    <a-card title="OCR性能监控" :bordered="false">
      <!-- 操作按钮 -->
      <div class="action-buttons" style="margin-bottom: 16px;">
        <a-button type="primary" @click="refreshStats" :loading="loading">
          <template #icon>
            <ReloadOutlined />
          </template>
          刷新统计
        </a-button>
        <a-button @click="resetStats" :loading="resetLoading" style="margin-left: 8px;">
          <template #icon>
            <DeleteOutlined />
          </template>
          重置统计
        </a-button>
      </div>

      <!-- 性能统计卡片 -->
      <a-row :gutter="16" style="margin-bottom: 24px;">
        <a-col :span="6">
          <a-statistic
            title="总处理页数"
            :value="performanceData.stats?.totalPagesProcessed || 0"
            :value-style="{ color: '#3f8600' }"
          />
        </a-col>
        <a-col :span="6">
          <a-statistic
            title="平均处理时间"
            :value="performanceData.stats?.averageProcessingTimeMs || 0"
            suffix="ms/页"
            :value-style="{ color: '#1890ff' }"
          />
        </a-col>
        <a-col :span="6">
          <a-statistic
            title="识别成功率"
            :value="performanceData.stats?.successRate || 0"
            suffix="%"
            :precision="2"
            :value-style="{ color: '#52c41a' }"
          />
        </a-col>
        <a-col :span="6">
          <a-statistic
            title="当前内存使用"
            :value="performanceData.currentMemoryUsageMB || 0"
            suffix="MB"
            :value-style="{ color: '#722ed1' }"
          />
        </a-col>
      </a-row>

      <!-- 详细统计信息 -->
      <a-row :gutter="16" style="margin-bottom: 24px;">
        <a-col :span="12">
          <a-card title="处理统计" size="small">
            <a-descriptions :column="1" bordered>
              <a-descriptions-item label="总处理时间">
                {{ formatTime(performanceData.stats?.totalProcessingTimeMs || 0) }}
              </a-descriptions-item>
              <a-descriptions-item label="成功识别页数">
                {{ performanceData.stats?.successfulOcrCount || 0 }}
              </a-descriptions-item>
              <a-descriptions-item label="识别失败页数">
                {{ performanceData.stats?.failedOcrCount || 0 }}
              </a-descriptions-item>
              <a-descriptions-item label="峰值内存使用">
                {{ performanceData.stats?.peakMemoryUsageMB || 0 }} MB
              </a-descriptions-item>
            </a-descriptions>
          </a-card>
        </a-col>
        <a-col :span="12">
          <a-card title="内存使用情况" size="small">
            <a-progress
              :percent="memoryUsage.usagePercent || 0"
              :format="(percent) => `${percent.toFixed(1)}%`"
              status="active"
            />
            <a-descriptions :column="1" size="small" style="margin-top: 16px;">
              <a-descriptions-item label="已用内存">
                {{ memoryUsage.usedMemoryMB || 0 }} MB
              </a-descriptions-item>
              <a-descriptions-item label="可用内存">
                {{ memoryUsage.freeMemoryMB || 0 }} MB
              </a-descriptions-item>
              <a-descriptions-item label="最大内存">
                {{ memoryUsage.maxMemoryMB || 0 }} MB
              </a-descriptions-item>
            </a-descriptions>
          </a-card>
        </a-col>
      </a-row>

      <!-- 优化建议 -->
      <a-card title="性能优化建议" size="small">
        <div v-if="performanceData.suggestions" class="suggestions">
          <div v-html="formatSuggestions(performanceData.suggestions)"></div>
        </div>
        <a-empty v-else description="暂无优化建议" />
      </a-card>
    </a-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { message } from 'ant-design-vue';
import { ReloadOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import { ocrPerformanceApi } from '@/api/business/pdf/ocr-performance-api';

// 响应式数据
const loading = ref(false);
const resetLoading = ref(false);
const performanceData = ref({});
const memoryUsage = ref({});
let refreshTimer = null;

// 获取性能统计信息
const getPerformanceStats = async () => {
  try {
    loading.value = true;
    const res = await ocrPerformanceApi.getPerformanceStats();
    if (res.code === 0) {
      performanceData.value = res.data;
    } else {
      message.error(res.msg || '获取性能统计失败');
    }
  } catch (error) {
    console.error('获取性能统计失败:', error);
    message.error('获取性能统计失败');
  } finally {
    loading.value = false;
  }
};

// 获取内存使用情况
const getMemoryUsage = async () => {
  try {
    const res = await ocrPerformanceApi.getMemoryUsage();
    if (res.code === 0) {
      memoryUsage.value = res.data;
    }
  } catch (error) {
    console.error('获取内存使用情况失败:', error);
  }
};

// 刷新统计
const refreshStats = async () => {
  await Promise.all([getPerformanceStats(), getMemoryUsage()]);
};

// 重置统计
const resetStats = async () => {
  try {
    resetLoading.value = true;
    const res = await ocrPerformanceApi.resetStats();
    if (res.code === 0) {
      message.success('统计信息已重置');
      await refreshStats();
    } else {
      message.error(res.msg || '重置统计失败');
    }
  } catch (error) {
    console.error('重置统计失败:', error);
    message.error('重置统计失败');
  } finally {
    resetLoading.value = false;
  }
};

// 格式化时间
const formatTime = (ms) => {
  if (ms < 1000) {
    return `${ms}ms`;
  } else if (ms < 60000) {
    return `${(ms / 1000).toFixed(1)}s`;
  } else {
    const minutes = Math.floor(ms / 60000);
    const seconds = ((ms % 60000) / 1000).toFixed(1);
    return `${minutes}分${seconds}秒`;
  }
};

// 格式化建议文本
const formatSuggestions = (suggestions) => {
  return suggestions.replace(/\n/g, '<br>');
};

// 自动刷新
const startAutoRefresh = () => {
  refreshTimer = setInterval(() => {
    getMemoryUsage(); // 只刷新内存使用情况，避免频繁请求性能统计
  }, 5000); // 每5秒刷新一次
};

// 停止自动刷新
const stopAutoRefresh = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer);
    refreshTimer = null;
  }
};

// 生命周期
onMounted(() => {
  refreshStats();
  startAutoRefresh();
});

onUnmounted(() => {
  stopAutoRefresh();
});
</script>

<style scoped>
.ocr-performance-container {
  padding: 24px;
}

.action-buttons {
  display: flex;
  align-items: center;
}

.suggestions {
  line-height: 1.6;
  color: #666;
}

.suggestions :deep(br) {
  margin-bottom: 8px;
}
</style> 